package phi.engine.actors
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	
	import phi.engine.core.GameTime;
	import phi.engine.draw.IDrawableSprite;
	import phi.engine.events.ActorEvent;

	public class VisualActor extends Actor implements IVisualActor
	{
		private var _costume :DisplayObject;

		public function VisualActor ( options :ActorOptions = null )
		{
			super( options );
		}

		// -----------------------------------------------------------------------------
		// Public Get/Set funcitons
		// -----------------------------------------------------------------------------

		public function get costume () :DisplayObject
		{
			return _costume;
		}

		public function set costume ( value :DisplayObject ) :void
		{
			destroyCostume();
			
			_costume = value;
			addChild( value );
			
			setCostumeOptions();
		}
		
		public function get costumeBounds():Rectangle
		{
			return getBounds( stage );
		}

		// -----------------------------------------------------------------------------
		// Public funcitons
		// -----------------------------------------------------------------------------

		override public function destroy () :void
		{
			super.destroy();
			destroyCostume();
		}
		
		override public function update(gameTime:GameTime):void
		{
			super.update(gameTime);

			//if( engine.debugDraw )
			//	costume.alpha = 0.3;
		}

		override public function draw ( gameTime :GameTime ) :void
		{
			if( costume is IDrawableSprite )
				IDrawableSprite( costume ).draw();
		}

		// -----------------------------------------------------------------------------
		// Protected funcitons
		// -----------------------------------------------------------------------------

		protected function createCostume () :void
		{
			costume = new Sprite();
		}

		protected function destroyCostume () :void
		{
			if ( costume != null )
			{
				try
				{
					removeChild( costume );
					costume = null;
				}
				catch ( e :Error )
				{
				}
				;
			}
		}

		protected function setCostumeOptions () :void
		{
			x = options.startPosition.x;
			y = options.startPosition.y;
		}

		override protected function optionsChangeHandler ( event :ActorEvent ) :void
		{
			if ( costume == null )
				createCostume();
		}
	}
}